#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<string>
#include<thread>

int socket_fd = -1;
uint16_t port;
std::string ip;

void Init()
{
    socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(socket_fd < 0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(0);
    }
}

void Receiver()
{
    while(true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        ssize_t ret = recvfrom(socket_fd, buffer, sizeof(buffer), 0, 
                              (struct sockaddr*)&temp, &len);
        if(ret > 0)
        {
            buffer[ret] = 0;
            std::cerr << buffer << std::endl;
        }
    }
}

void Sender()
{
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    while(true)
    { 
        std::cout << "Please Enter@ ";
        std::string line;
        std::getline(std::cin, line);
        // if(line.empty())
        //     continue;
        sendto(socket_fd, line.c_str(), line.size(), 0, 
              (struct sockaddr*)&server, sizeof(server));
    }
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << "ip port" << std::endl;
        exit(0);
    }
    ip = argv[1];
    port = std::stoi(argv[2]);
    Init();
    std::thread t_receive(Receiver);
    std::thread t_send(Sender);

    t_receive.join();
    t_send.join();
    
    return 0;
}